﻿using System;
using System.IO;
using System.Text;
using System.Data;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;
using System.Threading;
using System.Text.RegularExpressions;

namespace Warensoft.Utility
{
    public static  class Functions
    {
        const int EM_GETSEL = 0xB0;
        const int EM_LINEFROMCHAR = 0xC9;
        const int EM_LINEINDEX = 0xBB;
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
        int hwnd,
        int wMsg,
        int wParam,
        ref int lParam
        );

        /// <summary>
        /// 用于获取光标的坐标
        /// </summary>
        /// <param name="TextHwnd">文件句柄</param>
        /// <returns>坐标</returns>
        public static System.Drawing.Point GetCaretPos(int TextHwnd)
        {
            int LineNo, ColNo;
            int i = 0, j = 0, lParam = 0, wParam = 0, k = 0;
            i = SendMessage(TextHwnd, EM_GETSEL, wParam, ref lParam);
            j = i / 65536;
            LineNo = SendMessage(TextHwnd, EM_LINEFROMCHAR, j, ref lParam) + 1;
            k = SendMessage(TextHwnd, EM_LINEINDEX, -1, ref lParam);
            ColNo = j - k + 1;
            System.Drawing.Point point = new System.Drawing.Point(LineNo, ColNo);
            return point;
        }
        /// <summary>
        /// 换算文件长度
        /// </summary>
        /// <param name="length">文件长度</param>
        /// <returns>表示文件长度的字符串，以K，M，G为单位</returns>
        public static  string GetFileLength(long length)
        {
            long l = (long)length;
            string len = "";
            if (l < 1024 * 1024)
            {
                len = (l / 1024).ToString() + " K";
            }
            if (l > 1024 * 1024)
            {
                len = (l / (1024 * 1024)).ToString() + " M";
            }
            if (l > 1024 * 1024 * 1024)
            {
                len = (l / (1024 * 1024 * 1024)).ToString() + "G";
            }
            return len;
        }
        /// <summary>
        /// 生成Thunder下载地址
        /// </summary>
        /// <param name="code">资源实际下载地址</param>
        /// <returns>Thunder下载地址</returns>
        public static  string ThunderEncode(string code)
        {
            code = "AA" + code + "ZZ";
            string encode = "";
            byte[] bytes = System.Text.Encoding.GetEncoding(54936).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return "thunder://" + encode;
        } 
        public static void ZipFile(string strFile, string strZip)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
                strFile += Path.DirectorySeparatorChar;
            if (File.Exists(strZip)) File.Delete(strZip);
            ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
            s.SetLevel(6); // 0 - store only to 9 - means best compression
            zip(strFile, s);
            s.Finish();
            s.Close();
        }
        public static String ConvertDocToHTML(string path, Word.WdSaveFormat SaveFormat)
        {
            Word.Application newApp = new Word.Application();

            // 指定原文件和目标文件
            object Source = path;
            object Target = Path.GetTempPath() + Guid.NewGuid() + ".html";

            // 缺省参数  
            object Unknown = Type.Missing;

            //为了保险,只读方式打开
            object readOnly = true;

            // 打开doc文件
            Word.Document doc = newApp.Documents.Open(ref Source, ref Unknown,
                 ref readOnly, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown);

            // 指定另存为格式(rtf)
            object format = SaveFormat;

            // 转换格式
            doc.SaveAs(ref Target, ref format,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown);

            // 关闭文档和Word程序
            doc.Close(ref Unknown, ref Unknown, ref Unknown);
            newApp.Quit(ref Unknown, ref Unknown, ref Unknown);


            newApp = null;
            GC.Collect();
            return Target.ToString();

        }
        public static String ConvertDoc(string source,string destination, Word.WdSaveFormat saveFormat)
        {
            Word.Application newApp = new Word.Application();

            // 指定原文件和目标文件
            object Source = source;
            object Target = destination ;

            // 缺省参数  
            object Unknown = Type.Missing;

            //为了保险,只读方式打开
            object readOnly = true;

            // 打开doc文件
            Word.Document doc = newApp.Documents.Open(ref Source, ref Unknown,
                 ref readOnly, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown);

            // 指定另存为格式(rtf)
            object format = saveFormat  ;

            // 转换格式
            doc.SaveAs(ref Target, ref format,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown);

            // 关闭文档和Word程序
            doc.Close(ref Unknown, ref Unknown, ref Unknown);
            newApp.Quit(ref Unknown, ref Unknown, ref Unknown);


            newApp = null;
            GC.Collect();
            return Target.ToString();

        }
        private static void zip(string strFile, ZipOutputStream s)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
                strFile += Path.DirectorySeparatorChar;
            Crc32 crc = new Crc32();
            string[] filenames = Directory.GetFileSystemEntries(strFile);
            foreach (string file in filenames)
            {
                if (Directory.Exists(file))
                {
                    zip(file, s);
                }
                else
                {
                    //打开压缩文件
                    FileStream fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string tempfile = file.Substring(file.IndexOf(@"\") + 1);
                    ZipEntry entry = new ZipEntry(tempfile);
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;

                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }

        }

        public static string unZipFile(string TargetFile, string fileDir)
        {
            string rootFile = "";
            try
            {
                //读取压缩文件(zip文件)，准备解压缩
                ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
                ZipEntry theEntry;
                string path = fileDir; //解压出来的文件保存的路径

                string rootDir = ""; //根目录下的第一个子文件夹的名称
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    rootDir = Path.GetDirectoryName(theEntry.Name); //得到根目录下的第一级子文件夹的名称
                    if (rootDir.IndexOf("\\") >= 0)
                    {
                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                    }
                    string dir = Path.GetDirectoryName(theEntry.Name); //根目录下的第一级子文件夹的下的文件夹的名称
                    string fileName = Path.GetFileName(theEntry.Name); //根目录下的文件名称
                    if (dir != "" && fileName == "") //创建根目录下的子文件夹,不限制级别
                    {
                        if (!Directory.Exists(fileDir + "\\" + dir))
                        {
                            path = fileDir + "\\" + dir; //在指定的路径创建文件夹
                            Directory.CreateDirectory(path);
                        }
                    }
                    else if (dir == "" && fileName != "") //根目录下的文件
                    {
                        path = fileDir;
                        rootFile = fileName;
                    }
                    else if (dir != "" && fileName != "") //根目录下的第一级子文件夹下的文件
                    {
                        if (dir.IndexOf("\\") > 0) //指定文件保存的路径
                        {
                            path = fileDir + "\\" + dir;
                        }
                    }

                    if (dir == rootDir) //判断是不是需要保存在根目录下的文件
                    {
                        path = fileDir + "\\" + rootDir;
                    }

                    //以下为解压缩zip文件的基本步骤
                    //基本思路就是遍历压缩文件里的所有文件，创建一个相同的文件。
                    if (fileName != String.Empty)
                    {
                        FileStream streamWriter = File.Create(path + "\\" + fileName);

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                    }
                }
                s.Close();

                return rootFile;
            }
            catch (Exception ex)
            {
                return "1;" + ex.Message;
            }
        }
        static public string Encoding(string word)
        {
            byte[] words = System.Text.Encoding.Unicode.GetBytes(word);
            for (int i = 0; i < words.Length; i++)
            {
                words[i] += 57;
            }
            return System.Text.Encoding.Unicode.GetString(words);
        }
        static public string Decoding(string word)
        {
            byte[] words = System.Text.Encoding.Unicode.GetBytes(word);
            for (int i = 0; i < words.Length; i++)
            {
                words[i] -= 57;
            }
            return System.Text.Encoding.Unicode.GetString(words);
        }
        static public object get_XML_item(string xmlPath, string key)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlPath);
            return ds.Tables[0].Rows[0][key];
        }
        /// <summary>
        /// 返回服务器的名称
        /// </summary>
        /// <returns></returns>
        static public string get_server_name()
        {
            return System.Net.Dns.GetHostName();
        }
        /// <summary>
        /// 判断一个字符串是否为数字
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        static public bool is_numberic(string num)
        {

            try
            {
                System.Int32.Parse(num);
            }
            catch
            {
                return false;
            }
            return true;

        }
        /// <summary>
        /// 获取系统盘符
        /// </summary>
        /// <returns></returns>
        static public string system_driver()
        {
            return Path.GetPathRoot(Path.GetTempPath());
        }
        /// <summary>
        /// 获取汉字的大字首写字母
        /// </summary>
        /// <param name="strText">汉字串</param>
        /// <returns></returns>
        static public string GetChineseSpell(string strText)
        {
            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
                myStr += getSpell(strText.Substring(i, 1));
            }
            return myStr;
        }

        static private string getSpell(string cnChar)
        {
            byte[] arrCN = System.Text.Encoding.Default.GetBytes(cnChar);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return System.Text.Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return "*";
            }
            else return cnChar;
        }
        /// <summary>
        /// 生成一个以当前时间为号码的ID
        /// </summary>
        /// <returns></returns>
        static public string GetTimedID()
        {
            return DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
        }
        /// <summary>
        /// 关闭当前进程
        /// </summary>
        static public void KillCurrentProcess()
        {
            Process p = Process.GetCurrentProcess();
            p.Kill();
        }
        /// <summary>
        /// 递归拷贝所有子目录。
        /// </summary>
        /// <param name="sPath">源目录</param>
        /// <param name="dPath">目的目录</param>
        static public void copyDirectory(string sPath, string dPath)
        {
            string[] directories = System.IO.Directory.GetDirectories(sPath);
            if (!System.IO.Directory.Exists(dPath))
                System.IO.Directory.CreateDirectory(dPath);
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(sPath);
            System.IO.DirectoryInfo[] dirs = dir.GetDirectories();
            CopyFile(dir, dPath);
            if (dirs.Length > 0)
            {
                foreach (System.IO.DirectoryInfo temDirectoryInfo in dirs)
                {
                    string sourceDirectoryFullName = temDirectoryInfo.FullName;
                    string destDirectoryFullName = sourceDirectoryFullName.Replace(sPath, dPath);
                    if (!System.IO.Directory.Exists(destDirectoryFullName))
                    {
                        System.IO.Directory.CreateDirectory(destDirectoryFullName);
                    }
                    CopyFile(temDirectoryInfo, destDirectoryFullName);
                    copyDirectory(sourceDirectoryFullName, destDirectoryFullName);
                }
            }

        }

        /// <summary>
        /// 拷贝目录下的所有文件到目的目录。
        /// </summary>
        /// <param name="path">源路径</param>
        /// <param name="desPath">目的路径</param>
        static private void CopyFile(System.IO.DirectoryInfo path, string desPath)
        {
            string sourcePath = path.FullName;
            System.IO.FileInfo[] files = path.GetFiles();
            foreach (System.IO.FileInfo file in files)
            {
                string sourceFileFullName = file.FullName;
                string destFileFullName = sourceFileFullName.Replace(sourcePath, desPath);
                file.CopyTo(destFileFullName, true);
            }
        }
        static public bool IsEnglishWord(string Word)
        {
            return  Regex.IsMatch(Word, "[a-zA-Z]*");
            //char[] chars = Word.ToCharArray();
            //foreach (char c in chars)
            //{
            //    if (c < 65 || c > 122 || (c < 97 && c > 90))
            //    {
            //        return false;
            //    }
            //}
            //return true;
        }
        public static string EncodeBase64(string code)
        {
            string encode = "";
            byte[] bytes = System.Text.Encoding.Default.GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }

        public static string DecodeBase64(string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = System.Text.Encoding.Default.GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
        /// <summary>
        /// 获取任何文本中的单个英文单词
        /// </summary>
        /// <param name="AnyText">任何文本</param>
        /// <returns>单词数组</returns>
        static public string[] GetSingleWord(string AnyText)
        {
            MatchCollection matches = Regex.Matches(AnyText, "[a-zA-Z]+");
            string[] list = new string[matches.Count];
            for (int i = 0; i < matches.Count; i++)
            {
                list[i] = matches[i].Value;
            }
            return list;
        }
        public static byte[] BufferConnecter(params byte[][] BufferSequence)
        {
            System.Collections.Generic.List<byte> list = new System.Collections.Generic.List<byte>();
            foreach (byte[] item in BufferSequence )
            {
                foreach (byte b in item)
                {
                    list.Add(b);
                }
            }
            return list.ToArray();
        }
        public static byte[] GetSubArray(byte[] buffer, int start,int length)
        {
            System.Collections.Generic.List<byte> list = new System.Collections.Generic.List<byte>();
            for (int i = (start -1),Counter=0; Counter <=length  ; i++,Counter ++)
            {
                
                    list.Add(buffer[i]);
                
            }
            return list.ToArray();
        }
        /// <summary>
        /// 修改文件名
        /// </summary>
        /// <param name="oldPath">旧文件路径</param>
        /// <param name="newName">新文件路径</param>
        public static void Rename(string oldPath, string newName)
        {
            //Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(oldPath, newName);
            VB.VBFunctionClass.RenameFile(oldPath ,newName );
        }
        /// <summary>
        ///  修改文件夹名
        /// </summary>
        /// <param name="oldDir">旧目录</param>
        /// <param name="newName">新目录名</param>
        public static void RenameDirecory(string oldDir, string newName)
        {
            VB.VBFunctionClass.RenameDirectory(oldDir ,newName );
        }
    }
}
